package tq.com.tqteacher.activity.newPublish;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.githang.statusbar.StatusBarCompat;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import tq.com.systools.system.AlertDialogHelper;
import tq.com.systools.system.FileHelper;
import tq.com.systools.system.StringHelper;
import tq.com.tqcom.base.BaseActivity;
import tq.com.tqcom.net.INetCallback;
import tq.com.tqcom.net.TQNetResult;
import tq.com.tqcom.net.TQPictureUpload;
import tq.com.tqcom.util.TQLoadingHelper;
import tq.com.tqcom.util.TQSystemDefine;
import tq.com.tqcom.view.TQHeader5View;
import tq.com.tqteacher.R;
import tq.com.tqteacher.activity.TQDirectoryActivity;
import tq.com.tqteacher.activity.TQPdfReaderActivity;
import tq.com.tqteacher.activity.captureVideo.TQCaptureActivity;
import tq.com.tqteacher.model.TQAtachModel;
import tq.com.tqteacher.model.TQLogin;
import tq.com.tqteacher.model.TQNewPublish;
import tq.com.tqteacher.model.TQPublishType;
import tq.com.tqteacher.model.TQWKPublish;
import tq.com.tqteacher.net.TQNetInterface;
import tq.com.tqteacher.view.TQHeader3ViewHold;
import tq.com.upload.IUploadFileListener;
import tq.com.upload.TQUploadFileManager;

public class TQWKCaptureTypeActivity extends BaseActivity {
    private TQHeader5View mHeader5View;
    private EditText mEditText;
    private String coverFile;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wk_choicetype_layout);
        setStatusBar();

        mHeader5View = findViewById(R.id.title);
        mHeader5View.getTitleView().setText("微课");
        mHeader5View.getBackIcon().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TQWKCaptureTypeActivity.this.finish();
            }
        });

        mEditText = findViewById(R.id.title_input);
        findViewById(R.id.choice).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: ");
                choice();
            }
        });

        findViewById(R.id.capture).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: ");
                capture(null);
            }
        });

        findViewById(R.id.local_upload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: ");
                upload();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode != RESULT_OK) return;

        if(requestCode == 0x1){
            String file = data.getStringExtra(TQPdfReaderActivity.RESULT_KEY);
            Log.d(TAG, "onActivityResult: ");

            gotoCrop(file);
        }else if(requestCode == 0x02){
            ArrayList<String> file = (ArrayList<String>) data.getSerializableExtra(TQPdfReaderActivity.RESULT_KEY);
            Log.d(TAG, "onActivityResult: ");
            if(file.size() > 0){
                String pic = file.get(0);

                uploadCover(pic);
            }

        }else if(requestCode == 0x05){
            Uri lUri = data.getData();
            String file = lUri.getPath();
            
            try {
                String ff = FileHelper.getPath(this, lUri);
                Log.d(TAG, "onActivityResult: ");
                uploadFile(ff);
            }catch (Exception pE){
                pE.printStackTrace();
            }
        }else if(requestCode == 0x06){
            String file = data.getStringExtra(TQCaptureActivity.RESULT_KEY);
            Log.d(TAG, "onActivityResult: ");
            if(!StringHelper.isEmpty(file)){
                uploadFile(file);
            }
        }else if(requestCode == 0x07){
            Log.d(TAG, "onActivityResult: ");
            String file = data.getStringExtra("file");
            if(!StringHelper.isEmpty(file)){
                uploadAttach(file);
            }
        }
    }


    private void choice(){
        if(!checkTitle()){
            return;
        }

        TQDirectoryActivity.showSelect(this, 0x01, TQSystemDefine.FILE_TYPE_PDF);
    }

    private void capture(String file){
        if(!checkTitle()){
            return;
        }

        TQCaptureActivity.requestCapture(file, this, 0x06);
    }
    private void upload(){
        if(!checkTitle()){
            return;
        }

//        Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
//        intent.setType("video/mp4");
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        startActivityForResult(intent,0x05);

        TQDirectoryActivity.showSelect(this, 0x07, TQSystemDefine.FILE_TYPE_MP4);
    }

    private boolean checkTitle(){
        String sTile = StringHelper.editText(mEditText);
        if(StringHelper.isEmpty(sTile)){
            AlertDialogHelper.show(this, "标题不能为空");
            return false;
        }
        return true;
    }

    private void gotoCrop(String file){
        TQPdfReaderActivity.showCrop(this, file, 0x02, 1);
    }

    private void uploadCover(final String pCoverFile){
        TQLoadingHelper.build(this).setCancelable(false).show();
        TQLoadingHelper.setText("上传封面");

        TQPictureUpload.uploadPicture(pCoverFile, new INetCallback() {
            @Override
            public void result(TQNetResult pNetResult) {
                if(!pNetResult.isSuccess()){
                    TQLoadingHelper.setError("上传失败");
                    return;
                }

                TQLoadingHelper.dimiss();
                coverFile = TQPictureUpload.uploadResult(pNetResult);
                capture(pCoverFile);
            }
        });
    }
    private void uploadFile(String file){
        if(file == null)return;
        TQLoadingHelper.build(this).setCancelable(false).show();
        TQUploadFileManager.Build lBuild = new TQUploadFileManager.Build()
                .setFile(file)
                .setToken(TQLogin.getCurrent().getToken())
                .setListener(new IUploadFileListener() {
                    @Override
                    public void process(long current, long total) {
                        Log.d(TAG, "process: ");
                        TQLoadingHelper.setText(String.format("进度%d%%", (int)(current/(total*1.0f) * 100)));
                    }

                    @Override
                    public void fail(String msg) {
                        Log.d(TAG, "fail: ");
                        TQLoadingHelper.setError(msg);
                    }

                    @Override
                    public void success(String filePath) {
                        Log.d(TAG, "success: ");
                        TQLoadingHelper.dimiss();;

                        uploadAttach(filePath);
                    }
                });

        lBuild.start();

    }

    private void uploadAttach(String file){
        String sTile = StringHelper.editText(mEditText);
        final TQAtachModel lAtachModel = new TQAtachModel(file, coverFile);
        lAtachModel.setDesc(sTile);

        ArrayList<HashMap<String, String>> allAttach = new ArrayList<>();
        allAttach.add(lAtachModel.getHashInfo());

        TQLoadingHelper.build(this).setCancelable(false).show();
        TQNetInterface.attachFile2Material(TQPublishType.getSharePublishItem().getSeq_id(),
                allAttach, new INetCallback() {
                    @Override
                    public void result(TQNetResult pNetResult) {
                        if(!pNetResult.isSuccess()){
//                            AlertDialogHelper.show(TQWKCaptureTypeActivity.this, pNetResult.getErrMsg());
                            TQLoadingHelper.setError(pNetResult.getErrMsg());
                            return;
                        }

                        try{
                            if(pNetResult.getData() == null) return;

                            JSONObject save = pNetResult.getData().optJSONObject("saved");
                            if(save == null) return;

                            JSONArray attachs = save.optJSONArray("attachment");
                            if(attachs == null) return;

                            for (int i = 0; i < attachs.length(); i++){
                                JSONObject lObject = attachs.optJSONObject(0);
                                if(lObject == null)continue;

                                TQAtachModel lAtachModel1 = new TQAtachModel();
                                lAtachModel1.fromJson(lObject);

                                TQWKPublish lTQWKPublish = (TQWKPublish) TQPublishType.getSharePublishItem();
                                lTQWKPublish.addAttach(lAtachModel1);
                            }

                        }finally {
                            TQLoadingHelper.dimiss();
                        }
                        TQWKCaptureTypeActivity.this.finish();
                    }
                });
    }

}
